<?php

namespace App\Middleware;

use Closure;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class WeappAuth implements MiddlewareInterface
{
    /**
     * @param $request
     * @param Closure $next
     * @return mixed
     * @throws \Exception
     */
    public function process(Request $request, callable $next): Response
    {
        //白名单
        if(in_array($request->route->getPath(), config('weapp.ignore_urls', []))){
            return $next($request);
        }
        $auth_header = $request->header('Authorization');//获取token
        if (!$auth_header) return error('需要登录', [], 502);
        $header = $request->header();
//        if (isset($header['version-xcx']) && isset($header['timestmp-xcx']) && isset($header['random-xcx']) && isset($header['sign-xcx'])) {
//            $sign = md5('myshop' . $header['version-xcx'] . $header['timestmp-xcx'] . $header['random-xcx']);
//            if ($sign == $header['sign-xcx']) {
//                //有效期十分钟
//                if (abs(floor($header['timestmp-xcx'] / 1000) - time()) > 600) {
//                    return error('非法访问', [], 502);
//                }
//            } else {
//                return error('签名校验失败', [], 502);
//            }
//        } else {
//            return error('头部参数缺失', [], 502);
//        }

        // 解析token
        $auth_token_arr = explode(' ', $auth_header);
        if (count($auth_token_arr) != 2 || $auth_token_arr[0] != 'Bearer' || empty($auth_token_arr[1])) return error('需要登录', [], 502);
        $playLoad = decode_auth_token($auth_token_arr[1]);
        if ($playLoad['code'] !== 1) {
            return error('需要登录', $playLoad['data'], 502);
        }
        $userInfo = $playLoad['data'];
        $request->uid = $userInfo->id;
        return $next($request);

    }

}
